package com.tul.vapp.servicecenter.spring;

import java.util.List;
import java.util.Properties;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import com.tul.vapp.servicecenter.client.ClientFactory;
import com.tul.vapp.servicecenter.client.IConfigClient;

/**
 * Vapp自定义PlaceHolderConfigurer，迫使spring使用配置客户端获取配置
 * 
 * @author wwxiang
 * @since 2018/1/3.
 */
public class VappPlaceHolderConfigurer extends PropertyPlaceholderConfigurer implements InitializingBean {

	/**
	 * 用户在XML中指定
	 */
	private List<String> namespace;

	/**
	 * client
	 */
	protected IConfigClient client;

	@Override
	protected String resolvePlaceholder(String placeholder, Properties props) {
		String key = null;
		// spring 默认值用:分开
		if (placeholder.contains(":")) {
			key = placeholder.split(":")[0];
		} else {
			key = placeholder;
		}

		if (namespace == null) {
			// 用户没有指定命名空间，则全库搜索
			return client.getProperty(key);

		} else {
			// 用户指定了命名空间，则从指定的空间中搜索
			for (String ns : namespace) {
				String result = client.getProperty(ns, key);
				if (result != null) {
					return result;
				}
			}
		}
		return props.getProperty(placeholder);
	}

	public List<String> getNamespace() {
		return namespace;
	}

	public void setNamespace(List<String> namespace) {
		this.namespace = namespace;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		client = ClientFactory.getClient();
	}
}
